package cn.tedu.admin.mall.controller;

import cn.tedu.admin.mall.pojo.bo.CategoryBO;
import cn.tedu.admin.mall.pojo.param.CategoryAddParam;
import cn.tedu.admin.mall.pojo.param.CategoryUpdateParam;
import cn.tedu.admin.mall.pojo.po.CategoryPO;
import cn.tedu.admin.mall.pojo.vo.CategoryListItemVO;
import cn.tedu.admin.mall.pojo.vo.CategoryVO;
import cn.tedu.admin.mall.service.CategoryService;
import cn.tedu.tmall.common.vo.PageData;
import cn.tedu.tmall.common.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jdk.jfr.Category;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


//url 可以加版本号
//app 1.0   categories/list
//app 1.1  categories/list(arg)
//app 5.0  categories/list(arg,arg)
//app 强升
@Slf4j
@RequestMapping("/categories")
@RestController
@Api(tags = "类别管理")
@Validated
//todo 1 驗證框架不生效
//todo 2 接口文檔排序 不生效
// 提醒注意引入正確的包
public class CategoryController {

    //http://tea.mall/v1/category/list
    //http://tea.mall/category/add
    //http://tea.mall/category/info
    @Autowired
    private CategoryService categoryService;

    @ApiOperation("3 类别列表")
    //@ApiOperationSupport(order = 200)
    //@RequestMapping(value = "list",method = RequestMethod.GET)
    @GetMapping("/category/list/{pageNum}/{pageSize}")
    public JsonResult listCategory(
            @PathVariable
            @Range(min = 1,message = "请输入有效的pageNum")
                    Integer pageNum,
            @PathVariable
            @Range(min = 1,max = 50,message = "请输入有效的pageSize")
                    Integer pageSize){
        //1 pageSize 要做长度限制 假定 20,如果不做限制客户端传了一个很大的值50000,内存溢出 OutMemoryException
        //2 pageSize 可以不传,我们搞个默认值
        //pageNum 需要校验么? 大于0
        // 小于最大页数 太复杂,没必要,因为你传的再大或者再不合理,数据库不返回数据就行了
        log.debug("入参:pageNum:{},pageSize:{}",pageNum,pageSize);
        pageSize = pageSize == null ? 50 : pageSize;
        PageData<CategoryBO> categoryBOPageData = categoryService.listCategory(pageNum,pageSize);
        //从BO转换为VO
        PageData<CategoryListItemVO> result = new PageData<>();
        BeanUtils.copyProperties(categoryBOPageData,result);
        PageData<CategoryListItemVO> categoryBOPageData1 =
                getCategoryBOPageData(categoryBOPageData);
        return JsonResult.ok(categoryBOPageData1);
    }

    /**
     * 把PageData-list数据里的BO 转换为 CategoryListItemVO
     * @param pageData
     * @return
     */
    private PageData<CategoryListItemVO> getCategoryBOPageData(PageData<CategoryBO> pageData) {
        PageData<CategoryListItemVO> result = new PageData<>();
        List<CategoryBO> list = pageData.getList();
        List<CategoryListItemVO> categoryBOList = new ArrayList<>();
        for (CategoryBO categoryBO : list) {
            CategoryListItemVO categoryListItemVO = new CategoryListItemVO();
            BeanUtils.copyProperties(categoryBO,categoryListItemVO);
            categoryBOList.add(categoryListItemVO);
        }
        BeanUtils.copyProperties(pageData,result);
        result.setList(categoryBOList);
        return result;
    }


    //我们希望我们的所有controller 1 返回统一的格式 ,简化我们重复
    //如果正常支持的情况下,我们不想 CRUD create read update delete

    //@ApiOperationSupport(order = 100)
    @ApiOperation("1 添加类别")
    @PostMapping("/category/add")
    public JsonResult add(@Validated CategoryAddParam categoryAddParam){
        //打印日志的目的是为了出现问题好排查  问题 排查
        // 1都会出现什么问题?
        //    接口没找到
        //    插入的分类已经存在?
        //       1 前端的入参有问题
        //       2 我们的代码逻辑有问题;
        log.debug("开始处理添加分类请求,入参:{}",categoryAddParam);
        categoryService.addCategory(categoryAddParam);
        JsonResult jsonResult = JsonResult.ok();
        log.debug("时间 处理添加分类请求完成,入参:{},出参:{}",categoryAddParam,jsonResult);
        //jsonResult.setState(200);
        // jsonResult.setMessage("");
        // jsonResult.ok();
        return jsonResult;

        //前端老哥 有点疏忽, if state == 200 ,保存失败
    }
    //@ApiOperationSupport(order = 300)
    @ApiOperation("2 查询类别")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "类别id",required = true,dataType = "Long")
    })
    @GetMapping("/category/get/{id}")
    //category/del/{id}
    //category/enable/{id} category/{id}/enable
    //category/{id}/get
    public JsonResult getCategoryById(@PathVariable  Long id){
     CategoryBO categoryBO = categoryService.selectCategoryById(id);
     CategoryVO categoryVO = new CategoryVO();
     BeanUtils.copyProperties(categoryBO,categoryVO);
        return JsonResult.ok(categoryVO);
    }

    //@ApiOperationSupport(order = 400)
    @ApiOperation("4 修改类别")
    @PostMapping("/category/update/{id}")
    public JsonResult updateInfoById(@PathVariable @Range(min = 1, message = "请提交有效的类别ID值！") Long id,
                                     @Valid CategoryUpdateParam categoryUpdateParam) {
        log.debug("开始处理【修改类别详情】的请求，ID：{}，新数据：{}", id, categoryUpdateParam);
        categoryService.updateInfoById(id, categoryUpdateParam);
        return JsonResult.ok();
    }

    //@ApiOperationSupport(order = 500)
    @ApiOperation("5 删除类别")
    @PostMapping("/category/del/{id}")
    public JsonResult Category(@PathVariable Long id){
        log.debug("开始处理【根据ID删除类别】的请求，参数：{}", id);
        categoryService.delete(id);
        return JsonResult.ok();
    }
}
